﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Weight.Base
{
    public static  class ValidateProperty
    {
        public static Tuple<bool,string> Validate<T>(this T t)
        {
            Type type = t.GetType();
            List<string> list = new List<string>();
            //获取所有属性
            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            List<string> errorList = new List<string>();
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (propertyInfo.IsDefined(typeof(BaseAttribute)))//如果属性上有定义该属性,此步没有构造出实例
                {
                    foreach (BaseAttribute attribute in propertyInfo.GetCustomAttributes(typeof(BaseAttribute)))
                    {
                        if (!attribute.Validate(propertyInfo.GetValue(t, null)))
                        {
                            errorList.Add(attribute.error);
                        }
                    }

                }
            }
            string msg = string.Join(",", errorList).Trim();
            bool b = !string.IsNullOrEmpty(msg) ? false : true;
            Tuple<bool, string> result = new Tuple<bool, string>(b,msg);
            return result; 
        }
    }
}
